﻿using BBICMS.Infrastructure.UI;
using BBICMS.Model;
using BBICMS.Model.ViewModel.Back;
using BBICMS.Repository;
using BBICMS.WebUI.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using BBICMS.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using System.Xml.Linq;
using BBICMS.ViewModel;
using BBICMS.Resources;

namespace BBICMS.WebUI.Areas.Admin.Controllers
{
     [SIGAuth]
    
    public class News000Controller : BaseController
    {
       
        #region 新闻
        

        //
        // GET: /Admin/News/


       
        public ActionResult Index(int? page,int? blogId,string keyword)
        {
            //log = log4net.LogManager.GetLogger("File");
            // log.Info(string.Format("The user: {0} add Company to DB  [id:{1},header:{2}]", "sharon", "ddddd", "title"));

            //log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());
            //log.Info("Test message for Log4Net");  

            PostListVM vm = new PostListVM();

            vm.BlogId = blogId ?? 0;
            vm.Keyword = keyword;
            vm.Blogs = GetBlogList(blogId);
            vm.PageIndex = (page ?? 1) - 1; 
            vm.PageSize = SettingsManager.Article.PageSize;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            int count;

            var posts = _unit.Posts.GetPageArticles(vm.PageIndex, vm.PageSize, vm.BlogId, keyword, out count);
            vm.TotalCount = count;

            vm.PostList = new StaticPagedList<Post>(posts, vm.PageIndex + 1, vm.PageSize, vm.TotalCount);         

            return View(vm);
        }

        [HttpPost]
        public JsonResult UpdatePagesize(int pagesize)
        {           

            try
            {
                var xmlFile = Server.MapPath("~/Config/ArticleSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pagesize.ToString()); 
                doc.Save(xmlFile);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            //AR.Message = String.Format(Messages.AlertUpdateSuccess, "公司资料");
            return Json(AR, JsonRequestBehavior.DenyGet);
        }


       
        public ActionResult AddPost()
        {
            Post post = new Post();
            post.Active = true;

            var blogs = _unit.Blogs.GetAll().ToList(); 
            var lBlogs = new SelectList(blogs, "Id", "Title");
                         
            ViewBag.Categories = lBlogs;
            return View("AddPost", post);
        }


        [HttpPost]       
        [ValidateInput(false)]   
        public JsonResult AddPost(Post post)
        {
             
            if (ModelState.IsValid)
            {
                _unit.Posts.Add(post);
                _unit.SaveChanges();

                // TempData["message"] = string.Format("{0} 已经保存", site.Title);
                return Json(true, JsonRequestBehavior.DenyGet);

            }
            else
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }
            //   return RedirectToAction("Index");

        }

       
        public ActionResult EditPost(int Id)
        {
            var vPost = _unit.Posts.GetById(Id);
            if (vPost != null)
            {
                var blogs = _unit.Blogs.GetAll().ToList();
                var lBlogs = new SelectList(blogs, "Id", "Title");

                ViewBag.Categories = lBlogs;

                return View(vPost);
            }
            return View("NotFound");
        }

        [HttpPost]
        [ValidateInput(false)]
         
        public JsonResult EditPost(Post post)
        {


            //site.UpdatedBy = User.Identity.Name;
            //site.UpdatedDate = DateTime.Now;   

            if (ModelState.IsValid)
            {
                _unit.Posts.Update(post);
                _unit.SaveChanges();
                return Json(true, JsonRequestBehavior.DenyGet);

            }
            else
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }

        }

        [HttpPost]
        public JsonResult IsActive(int id)
        {
            var post = _unit.Posts.GetById(id);
            if (post != null)
            {
                post.Active = !post.Active;
                _unit.Posts.Update(post);
                _unit.SaveChanges();

                AR.SetSuccess("设置成功");
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            AR.Setfailure("设置失败");
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult DeletePost(int id)
        {

            Post vPost = _unit.Posts.GetById(id);

            if (vPost != null)
            {
                //string imgurl = Server.MapPath(vBlog.ImageURL);
                //if (System.IO.File.Exists(imgurl))
                //{
                //    System.IO.File.Delete(imgurl);    //删除缩略图
                //}

                _unit.Posts.Delete(vPost);
                _unit.SaveChanges();
                AR.SetSuccess(string.Format(Messages.AlertDeleteSuccess, EntityNames.Article));
                return Json(AR, JsonRequestBehavior.DenyGet);
              
            }
            AR.Setfailure(string.Format(Messages.AlertDeleteFailure, EntityNames.Article));
            return Json(AR, JsonRequestBehavior.DenyGet);           
        }

        #endregion


        #region 新闻分类
       

       
        public ActionResult Blogs(int page = 1)
        {
            //log = log4net.LogManager.GetLogger("File");
            // log.Info(string.Format("The user: {0} add Company to DB  [id:{1},header:{2}]", "sharon", "ddddd", "title"));

            //log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());
            //log.Info("Test message for Log4Net"); 

            int PageSize = BBICMS.Infrastructure.Helpers.Settings.PageSize;

            BlogListVM BlogList = new BlogListVM
            {
                Blogs = _unit.Blogs.GetAll().OrderByDescending(s => s.Importance)
                     .Skip((page - 1) * PageSize)
                     .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = _unit.Blogs.GetAll().Count()
                }
            };

            return View(BlogList);
        }

       
        public ActionResult AddBlog()
        {
            Blog vBlog = new Blog();
            vBlog.Active = true;
            vBlog.Importance = 0;

            return View("AddBlog", vBlog);
        }


        [HttpPost]
       
        public JsonResult AddBlog(Blog blog)
        {



            if (ModelState.IsValid)
            {
                _unit.Blogs.Add(blog);
                _unit.SaveChanges();

                // TempData["message"] = string.Format("{0} 已经保存", site.Title);
                return Json(true, JsonRequestBehavior.DenyGet);

            }
            else
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }
            //   return RedirectToAction("Index");

        }


       
        public ActionResult EditBlog(int Id)
        {
            var vSlider = _unit.Blogs.GetById(Id);
            if (vSlider != null)
            {
                return View(vSlider);
            }
            return View("NotFound");
        }

        [HttpPost]

        public JsonResult EditBlog(Blog blog)
        {


            //site.UpdatedBy = User.Identity.Name;
            //site.UpdatedDate = DateTime.Now;   

            if (ModelState.IsValid)
            {
                _unit.Blogs.Update(blog);
                _unit.SaveChanges();
                return Json(true, JsonRequestBehavior.DenyGet);

            }
            else
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }

        }

        // DELETE: /User/DeleteSite
        [HttpDelete]
        public JsonResult DeleteBlog(int id)
        {

            Blog vBlog = _unit.Blogs.GetById(id);

            if (vBlog != null)
            {
                //string imgurl = Server.MapPath(vBlog.ImageURL);
                //if (System.IO.File.Exists(imgurl))
                //{
                //    System.IO.File.Delete(imgurl);    //删除缩略图
                //}

                _unit.Blogs.Delete(vBlog);
                _unit.SaveChanges();
                return Json(true, JsonRequestBehavior.DenyGet);
            }

            return Json(false, JsonRequestBehavior.DenyGet);
        }

        public List<SelectListItem> GetBlogList(int? blogId){
            var blogs = _unit.Blogs.GetAll().OrderByDescending(b => b.Importance).ThenByDescending(b => b.AddedDate).ToList();
            List<SelectListItem> lBlogs = new List<SelectListItem>();
            foreach (var blog in blogs)
            {
                SelectListItem sli = new SelectListItem();
                sli.Text = blog.Title;
                sli.Value = blog.Id.ToString();
                sli.Selected = (blogId == blog.Id);   

                lBlogs.Add(sli);               
                
            }
            lBlogs.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });
                  
            return lBlogs;
        }
        #endregion
    }
}
